import React from 'react';
import { List } from 'antd';
import { queryCurrent,updatePassword,updatePhone,getCode } from '../service';
import { Link, useRequest } from 'umi';
import { useState,useEffect } from 'react';
import { Modal, Form, Input, Button, Descriptions,Popover,Progress,Select,Row,Col,message   } from 'antd';
import md5 from 'js-md5';
import styles from '../style.less';

const FormItem = Form.Item;
const { Option } = Select;
const InputGroup = Input.Group;
type Unpacked<T> = T extends (infer U)[] ? U : T;

const passwordStrength = {
  strong: <span className="strong">强</span>,
  medium: <span className="medium">中</span>,
  weak: <span className="weak">弱 Weak</span>,
};

const passwordStatusMap = {
  ok: (
    <div className={styles.success}>
      <span>强度：强</span>
    </div>
  ),
  pass: (
    <div className={styles.warning}>
      <span>强度：中</span>
    </div>
  ),
  poor: (
    <div className={styles.error}>
      <span>强度：太短</span>
    </div>
  ),
};

const passwordProgressMap: {
  ok: 'success';
  pass: 'normal';
  poor: 'exception';
} = {
    ok: 'success',
    pass: 'normal',
    poor: 'exception',
  };

const SecurityView: React.FC = () => {
   const [count, setCount]: [number, any] = useState(0);
    const [open, setOpen] = useState(false);
    const [updateOpen, setUpdateOpen] = useState(false);
      const [form] = Form.useForm();
      const [phoneForm] = Form.useForm();
        const confirmDirty = false;
        const [visible, setVisible]: [boolean, any] = useState(false);
          const [popover, setPopover]: [boolean, any] = useState(false);
 const [prefix, setPrefix]: [string, any] = useState('86');
            const changePrefix = (value: string) => {
    setPrefix(value);
  };
            const { data: currentUser, loading } = useRequest(() => {
    return queryCurrent();
  });
          const checkConfirm = (_: any, value: string) => {
    const promise = Promise;
    if (value && value !== form.getFieldValue('password')) {
      return promise.reject('两次输入的密码不匹配!');
    }
    return promise.resolve();
  };

  const checkPassword = (_: any, value: string) => {
    const promise = Promise;
    // 没有值的情况
    if (!value) {
      setVisible(!!value);
      return promise.reject('请输入密码!');
    }
    // 有值的情况
    if (!visible) {
      setVisible(!!value);
    }
    setPopover(!popover);
    if (value.length < 6) {
      return promise.reject('');
    }
    if (value && confirmDirty) {
      form.validateFields(['confirm']);
    }
    return promise.resolve();
  };

  const getData = () => [
    {
      title: '账户密码',
      actions: [<a key="Modify"  onClick={() => {
         form.resetFields();
                      setOpen(true);
                    }}>修改</a>],
    },
    {
      title: '密保手机',
      description: (
        <>
        已绑定手机:
          {currentUser?currentUser.phone:"" }
        </>
      ),
actions: [<a key="Modify" onClick={() => {
    phoneForm.resetFields();
                      setUpdateOpen(true);
                    }}>修改</a>],
    }
  ];
    const getPasswordStatus = () => {
    const value = form.getFieldValue('password');
    if (value && value.length > 9) {
      return 'ok';
    }
    if (value && value.length > 5) {
      return 'pass';
    }
    return 'poor';
  };

    const renderPasswordProgress = () => {
    const value = form.getFieldValue('password');
    const passwordStatus = getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  let interval: number | undefined;
  useEffect(
    () => () => {
      clearInterval(interval);
    },
    [interval],
  );

  const onGetCaptcha = async () => {
    let counts = 59;
    setCount(counts);
    interval = window.setInterval(() => {
      counts -= 1;
      setCount(counts);
      if (counts === 0) {
        clearInterval(interval);
      }
    }, 1000);
    const value = phoneForm.getFieldValue('phone');
    const response = await getCode({
      phone: value,
    });
    if (response.code == 200) {
      message.success('发送成功');
    } else {
      message.error('发送失败!');
    }
  };

  const update = async (item: Object) => {
    const hide = message.loading('正在更新');
    try {
           let response = null;
      if(item.type==0)
      {
         response = await updatePassword(item);
      }
      else
      {
        response = await updatePhone(item);
      }
 
      if (response.code == 200) {
        message.success('更新成功');
        if (open) {
          setOpen(false);
        }
        if (updateOpen) {
          setUpdateOpen(false);
          currentUser.phone=item.phone;
        }
      } else {
        message.error(response.message);
      }
      hide();
    } catch (error) {
      console.log("error",error);
      hide();
      message.error('更新失败');
      return false;
    }
  };


const data = getData();
return (
    <>
  <List<Unpacked<typeof data>>
        itemLayout="horizontal"
        dataSource={data}
    renderItem={(item) => (
      <List.Item actions={item.actions}>
        <List.Item.Meta title={item.title} description={item.description} />
      </List.Item>
    )}
    />
         <Modal
        open={open}
        title="修改密码"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setOpen(false);
        }}

        onOk={() => {
          form
            .validateFields()
            .then((values) => {
               values.password = md5(values.password);
               values.id=currentUser.id;
                values.type=0;
               update(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          name="form_in_modal"
                    labelCol={{ span: 6 }}
      wrapperCol={{ span: 16 }}
        >
         <Popover
          getPopupContainer={(node) => {
            if (node && node.parentNode) {
              return node.parentNode as HTMLElement;
            }
            return node;
          }}
          content={
            visible && (
              <div style={{ padding: '4px 0' }}>
                {passwordStatusMap[getPasswordStatus()]}
                {renderPasswordProgress()}
                <div style={{ marginTop: 10 }}>
                  <span>请至少输入 6 个字符。请不要使用容易被猜到的密码。</span>
                </div>
              </div>
            )
          }
          overlayStyle={{ width: 240 }}
          placement="right"
          visible={visible}
        >
           <FormItem
            name="password"
             label="新密码"
            rules={[
            {
              required: true,
              message: '确认密码',
            },
          ]}
            className={
              form.getFieldValue('password') &&
              form.getFieldValue('password').length > 0 &&
              styles.password
            }
            rules={[
              {
                validator: checkPassword,
              },
            ]}
          >
            <Input size="large" type="password" placeholder="至少6位密码，区分大小写" />
          </FormItem>
        </Popover>
        <FormItem
          name="confirm"
          label="确认密码"
          rules={[
            {
              required: true,
              message: '确认密码',
            },
            {
              validator: checkConfirm,
            },
          ]}
        >
          <Input size="large" type="password" placeholder="确认密码" />
        </FormItem>
        </Form>
      </Modal>
       <Modal
        open={updateOpen}
        title="更换手机号"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setUpdateOpen(false);
        }}

        onOk={() => {
          phoneForm
            .validateFields()
            .then((values) => {
                values.id=currentUser.id;
                values.type=1;
               update(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
              <Form
                form={phoneForm}
        >
                <InputGroup compact>
          <Select size="large" value={prefix} onChange={changePrefix} style={{ width: '20%' }}>
            <Option value="86">+86</Option>
            <Option value="87">+87</Option>
          </Select>
          <FormItem
            style={{ width: '70%' }}
            name="phone"
            rules={[
              {
                required: true,
                message: '请输入手机号!',
              },
              {
                pattern: /^\d{11}$/,
                message: '手机号格式错误!',
              },
            ]}
          >
            <Input size="large" placeholder="手机号" />
          </FormItem>
        </InputGroup>
        <Row gutter={8}>
          <Col span={16}>
            <FormItem
              name="smsCode"
              rules={[
                {
                  required: true,
                  message: '请输入验证码!',
                },
              ]}
            >
              <Input size="large" placeholder="验证码" />
            </FormItem>
          </Col>
          <Col span={8}>
            <Button
              size="large"
              disabled={!!count}
              className={styles.getCaptcha}
              onClick={onGetCaptcha}
            >
              {count ? `${count} s` : '获取验证码'}
            </Button>
          </Col>
        </Row>
         </Form>
      </Modal>
    </>
  );
};

export default SecurityView;
